package start;

import java.io.IOException;
import java.util.ConcurrentModificationException;
import java.util.Vector;

import IO.Log;
import IO.Save;

import web.Downloader;
import web.PopulateShow;
import data.Show;
import data.Status.StatusEnum;

//@Jen - need a thread suiside method.
/**@quinn - need to learn how to spell suicide */
public class Heartbeat implements Runnable
{
	/**
	 * The show list to check for updates for. 
	 */
	private Vector<Show> showList;

	/**
	 * Constructor
	 * @param showList - shallow copy of the showlist to update.
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public Heartbeat(Vector<Show> showList) throws IOException, InterruptedException
	{
		this.showList = showList;
	}
	
	
	
	/**
	 * Method used to run Heartbeat as a thread. 
	 * Also checks for show updates every hour.
	 */
	public void run()
	{
		boolean alive = true;
		while(alive)
		{
			try{
				while(showList.size() == 0);
				for(Show s : showList)
				{
					PopulateShow popShow = new PopulateShow(s.getShowName());
					boolean isShowPopulated = popShow.updateShow(s);
					popShow = null;
					if(isShowPopulated)
					{
						//Log.println("["+new Date().toString()+" : "+s.getShowName()+"] Show updated!");
						
						//Show has been updated!  If the show wasn't set on CHECK, attempt to goToNext
						if(s.getStatus() != StatusEnum.CHECK)
						{
							if(s.goToNextEpisode())
							{
								s.setStatus(StatusEnum.CHECK);
							}
						}
					}
					else
					{
						//Log.println("["+new Date().toString()+" : "+s.getShowName()+"] nothing new");
					}
					
					//If the show is set to CHECK, kick off that downloader!
					if(s.getStatus() == StatusEnum.CHECK)
					{
						//go-go gadget downloader!
						new Downloader(s);
					}
					
				}
				Save.saveShows(showList);

				long startTime = System.currentTimeMillis();
				long startMemory = Runtime.getRuntime().freeMemory();
				System.gc();
				long endTime = System.currentTimeMillis();
				long endMemory = Runtime.getRuntime().freeMemory();
				Log.println("GC took "+Long.toString((endTime-startTime)/1000)+" Saved: "+Long.toString(endMemory-startMemory)+"bytes\n");				
				try {
					
					Thread.sleep(1000*60*30); // 1000 sec/millisec * 60 min/sec * 60 hour/min * 1/2 == 1/2 hour. 
					//Thread.sleep(1000*30); //30 seconds. For testing.
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
				}
			}
			catch (ConcurrentModificationException e)
			{
				Log.printErrorln(e.getLocalizedMessage());
			}
		}
	}
}
